Page({
    data: {
        products:[],
        currentProduct: null,
        cmtVisible:false,
        cmtText:'',
        cmtPid:null
    },

    onLoad(options){
        // 获取产品ID
        const {id} = options
        // 从缓存读取最新数据
        const products = wx.getStorageSync('products') || this.initProducts()
        // 查找对应产品
        const currentProduct = products.find(p => p.id == id)
        this.setData({products, currentProduct})
        // 设置导航栏标题
        wx.setNavigationBarTitle({title: currentProduct ? currentProduct.title : '产品详情'})
      },

    onShow(){
        // 从缓存读取最新数据
        const products = wx.getStorageSync('products') || this.initProducts()
        // 无论是否有currentProduct，都重新设置products数据
        this.setData({products})
        // 如果已有选中的产品，更新它的数据
        if(this.data.currentProduct){
          const updatedProduct = products.find(p => p.id == this.data.currentProduct.id)
          this.setData({currentProduct: updatedProduct})
        }
      },
      initProducts(){
        const list = [
            {id:1,title:'鲜肉月饼',price:7999,thumb:'https://ts1.tc.mm.bing.net/th/id/OIP-C.Fe3G12jGnzA5-E9ozhJ5HAHaLH?rs=1&pid=ImgDetMain&o=7&rm=3=鲜肉月饼'},
            {id:2,title:'',price:1899,thumb:'https://img.shetu66.com/2023/11/24/1700771295543366.png=大麦茶'}
        ]
        wx.setStorageSync('products',list)
        return list
      },
    /* 点赞 */
    like(e){
        const id = e.currentTarget.dataset.id
        const products = wx.getStorageSync('products')
        const p = products.find(v=>v.id===id)
        if(!p.comment.liked){
          p.comment.likes = (p.comment.likes||0)+1
          p.comment.liked = true
        }else{
          p.comment.likes -= 1
          p.comment.liked = false
        }
        wx.setStorageSync('products',products)
        this.setData({products})
      },
    
      /* 评论相关 */
      showCmtInput(e){
        this.setData({cmtVisible:true,cmtPid:e.currentTarget.dataset.id,cmtText:''})
      },
      onCmtInput(e){this.setData({cmtText:e.detail.value})},
      sendCmt(){
        if(!this.data.cmtText.trim()) return
        const products = wx.getStorageSync('products')
        const p = products.find(v=>v.id===this.data.cmtPid)
        if(!p.comment.replies) p.comment.replies=[]
        p.comment.replies.push({nick:'微信用户',text:this.data.cmtText})
        wx.setStorageSync('products',products)
        this.setData({products,cmtVisible:false})
      },

    // 关闭评论弹窗
    closeCmt(){
        this.setData({cmtVisible:false})
      },

    // 阻止事件冒泡
    stopPropagation(){
        // 空函数，仅用于阻止事件冒泡
      },

    // 跳转到评论页面
    goToComment(){
        if(this.data.currentProduct){
          wx.navigateTo({
            url: `/pages/comment/comment?id=${this.data.currentProduct.id}`
          })
        }
      },
    
      /* 预览图片 */
      preview(e){
        wx.previewImage({urls:[e.currentTarget.dataset.src]})
      },
  
    // 加载朋友圈数据
    loadMomentData(index) {
      const storedMoments = wx.getStorageSync('momentsData') || [];
      this.setData({
        moment: storedMoments[index]
      });
    },
  
    // 点赞功能
    toggleLike() {
      const storedMoments = wx.getStorageSync('momentsData') || [];
      const currentMoment = storedMoments[this.data.index];
      
      if (currentMoment.isLiked) {
        // 取消点赞
        currentMoment.isLiked = false;
        currentMoment.likeCount--;
      } else {
        // 点赞
        currentMoment.isLiked = true;
        currentMoment.likeCount++;
      }
      
      storedMoments[this.data.index] = currentMoment;
      wx.setStorageSync('momentsData', storedMoments);
      
      this.setData({
        moment: currentMoment
      });
      
      wx.showToast({
        title: currentMoment.isLiked ? '点赞成功' : '取消点赞',
        icon: 'none'
      });
    },
  
    // 显示评论输入框
    showCommentInput() {
      this.setData({
        showCommentInput: true,
        commentContent: ''
      });
      
      // 自动聚焦，弹出键盘
      setTimeout(() => {
        const query = wx.createSelectorQuery();
        query.select('#commentInput').focus();
        query.exec();
      }, 100);
    },
  
    // 评论内容变化
    onCommentChange(e) {
      this.setData({
        commentContent: e.detail.value
      });
    },
  
    // 发送评论
    sendComment() {
      const content = this.data.commentContent.trim();
      if (!content) {
        wx.showToast({
          title: '评论不能为空',
          icon: 'none'
        });
        return;
      }
  
      const storedMoments = wx.getStorageSync('momentsData') || [];
      const currentMoment = storedMoments[this.data.index];
      
      // 初始化评论数组
      if (!currentMoment.comments) {
        currentMoment.comments = [];
      }
      
      // 添加新评论
      currentMoment.comments.push({
        user: '我',
        content: content,
        time: this.formatTime(new Date())
      });
      
      // 更新评论数量
      currentMoment.commentCount = currentMoment.comments.length;
      
      // 保存数据
      storedMoments[this.data.index] = currentMoment;
      wx.setStorageSync('momentsData', storedMoments);
      
      // 更新页面
      this.setData({
        moment: currentMoment,
        commentContent: '',
        showCommentInput: false
      });
      
      wx.showToast({
        title: '评论成功',
        icon: 'none'
      });
    },
  
    // 分享功能
    onShareAppMessage() {
      const moment = this.data.moment;
      return {
        title: '朋友圈分享',
        path: '/pages/detail/detail?index=' + this.data.index,
        imageUrl: moment.images.length > 0 ? moment.images[0] : ''
      };
    },
  
    // 格式化时间
    formatTime(date) {
      const hour = date.getHours();
      const minute = date.getMinutes();
      return `${this.padZero(hour)}:${this.padZero(minute)}`;
    },
  
    // 补零
    padZero(n) {
      return n < 10 ? `0${n}` : n;
    }
  });
      